//
//  CMBankPerfInformatCtrl.m
//  CreditManger
//
//  Created by 于会海 on 15/11/10.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMBankPerfInformatCtrl.h"
#import "CheckValid.h"
#import "CMLoginManager.h"
#import "CMLoginUserInfo.h"
#import "UIImageView+WebCache.h"
#import "CMRegistGetMsgCodeInfo.h"
#import "CMRegistGetMsgCodeParam.h"
#import "CMRegistGetMsgCodeParser.h"
#import "CMBankFinalRegistCtrl.h"
#import "CMRegistSecondStepParam.h"
#import "CMRegistSecondStepParser.h"

@interface CMBankPerfInformatCtrl ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *topImageView;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UITextField *rePassword;
@property (weak, nonatomic) IBOutlet UITextField *phoneNum;
@property (weak, nonatomic) IBOutlet UITextField *verCode;
@property (weak, nonatomic) IBOutlet UIButton *reGetBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
- (IBAction)reGetBtnClicked:(id)sender;
- (IBAction)nextBtnClicked:(id)sender;

@end
@implementation CMBankPerfInformatCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)buildLayout{
    self.title = @"央行征信注册";
    [self showDoneWithTitle:@"已有账号"];
    self.userName.delegate = self;
    self.password.delegate = self;
    self.rePassword.delegate = self;
    self.phoneNum.delegate = self;
    self.verCode.delegate = self;
    self.nextBtn.layer.cornerRadius = 4.0;
    [self setTimerDefault];
}
- (void)setTimerDefault{
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 120] forKey:REGIST_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)doDone{
    LLog(@"已有账号");
}

#pragma mark -TextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 40 - (self.view.frame.size.height - 216.0 -60 -64);
    [UIView animateWithDuration:0.3 animations:^{
        if(offset > 0){
            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        }
    }];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.userName resignFirstResponder];
    [self.password resignFirstResponder];
    [self.rePassword resignFirstResponder];
    [self.verCode resignFirstResponder];
    [self.phoneNum resignFirstResponder];
    self.view.frame =CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
}


- (IBAction)reGetBtnClicked:(id)sender {
    LLog(@"重新获取验证码");
    [self makeTime];
    [self requestMobileCode];
}

- (IBAction)nextBtnClicked:(id)sender {
    LLog(@"下一步");
    if ([CheckValid checkStrIsEmpty:self.userName.text]) {
        [self.userName becomeFirstResponder];
        DISSMISS_ERRView(@"用户名不能为空",[[[UIApplication sharedApplication] windows] lastObject]);
    }
    if ([CheckValid checkStrIsEmpty:self.phoneNum.text]) {
        [self.phoneNum becomeFirstResponder];
        DISSMISS_ERRView(@"手机号不能为空",[[[UIApplication sharedApplication] windows] lastObject]);
    }
    if ([CheckValid checkStrIsEmpty:self.password.text]) {
        [self.password becomeFirstResponder];
        DISSMISS_ERRView(@"密码不能为空",[[[UIApplication sharedApplication] windows] lastObject]);
    }
    if ([CheckValid checkStrIsEmpty:self.rePassword.text]) {
        [self.rePassword becomeFirstResponder];
        DISSMISS_ERRView(@"请再次输入密码",[[[UIApplication sharedApplication] windows] lastObject]);
    }
    if ([CheckValid checkStrIsEmpty:self.verCode.text]) {
        [self.verCode becomeFirstResponder];
        DISSMISS_ERRView(@"验证码不能为空",[[[UIApplication sharedApplication] windows] lastObject]);
    }
    CMRegistSecondStepParser* parser = [[CMRegistSecondStepParser alloc] init];
    CMRegistSecondStepParam* param = [[CMRegistSecondStepParam alloc] init];
    param.uid = [CMLoginManager getCurrentUserFromUserdefault].uid;
    param.token = [CMLoginManager getCurrentUserFromUserdefault].token;
    param.timeuint = self.timeunit;
    param.quantGroupToken = self.quantGroupToken;
    param.cardNo = [CMLoginManager getCurrentUserFromUserdefault].cardno;
    param.userName = self.userName.text;
    param.mobile = self.phoneNum.text;
    param.password = self.password.text;
    param.confirmePassword = self.rePassword.text;
    param.email = @"";
    param.authCode = self.verCode.text;
    
    [NetCenter postDataFromURL:Method_registSecondStep params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            CMBankFinalRegistCtrl* finalVC = [[CMBankFinalRegistCtrl alloc] init];
            [self.navigationController pushViewController:finalVC animated:YES];
        }else{
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
}

- (void)requestMobileCode{
    CMLoginUserInfo* info = [CMLoginManager getCurrentUserFromUserdefault];
    CMRegistGetMsgCodeParser* parser = [[CMRegistGetMsgCodeParser alloc] init];
    CMRegistGetMsgCodeParam*  param  = [[CMRegistGetMsgCodeParam alloc] init];
    param.uid             = info.uid;
    param.token           = info.token;
    param.mobile          = info.mobile;
    param.timeuint        = self.timeunit;
    param.quantGroupToken = self.quantGroupToken;
    [NetCenter postDataFromURL:Method_registGetMsgCode params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            CMRegistGetMsgCodeInfo* codeInfo = (CMRegistGetMsgCodeInfo*)myResult.result;
            self.verCode.text = codeInfo.dataInfo;
            LLog(@"发送验证码成功");
        }else{
           DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
}
- (void)makeTime{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSTimeInterval timeLast = [[[NSUserDefaults standardUserDefaults] objectForKey:REGIST_CODE_TIME] longLongValue];
        if (timeLast <= 0){
            self.reGetBtn.enabled = YES;
            [self.reGetBtn setTitle:@"" forState:UIControlStateNormal];
            [self.reGetBtn setTitle:@"" forState:UIControlStateDisabled];
            return;
        }
        NSTimeInterval now = [NSDate date].timeIntervalSince1970;
        if (now >= timeLast){
            self.reGetBtn.enabled = YES;
            [self.reGetBtn setTitle:@"" forState:UIControlStateNormal];
            [self.reGetBtn setTitle:@"" forState:UIControlStateDisabled];
            self.reGetBtn.backgroundColor = [UIColor clearColor];
            return;
        }
        self.reGetBtn.enabled = NO;
        [self.reGetBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",(int)(timeLast- now)] forState:UIControlStateNormal];
        [self.reGetBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",(int)(timeLast- now)] forState:UIControlStateDisabled];
        [self performSelector:@selector(makeTime) withObject:nil afterDelay:0.01];
    });
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(makeTime) object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = NO;
    [self setTimerDefault];
    [self makeTime];
    [self requestMobileCode];
}

@end
